const Order = require('../models/order.model');
const ApiError = require('../utils/ApiError');

class OrderService {
    /**
     * 获取订单列表
     * @param {Object} filter - 过滤条件
     * @param {Object} options - 分页选项
     * @returns {Promise<Order[]>}
     */
    async getOrders(filter = {}, options = {}) {
        const orders = await Order.find(filter)
            .sort({ createdAt: -1 })
            .skip(options.skip)
            .limit(options.limit)
            .populate('user', 'name email')
            .populate('items.product', 'name price');
        return orders;
    }

    /**
     * 获取单个订单详情
     * @param {string} orderId - 订单ID
     * @returns {Promise<Order>}
     */
    async getOrder(orderId) {
        const order = await Order.findById(orderId)
            .populate('user', 'name email')
            .populate('items.product', 'name price');
        
        if (!order) {
            throw new ApiError(404, '订单不存在');
        }
        return order;
    }

    /**
     * 更新订单状态
     * @param {string} orderId - 订单ID
     * @param {string} status - 新状态
     * @returns {Promise<Order>}
     */
    async updateOrderStatus(orderId, status) {
        const validStatuses = ['pending', 'processing', 'shipped', 'delivered', 'cancelled'];
        
        if (!validStatuses.includes(status)) {
            throw new ApiError(400, '无效的订单状态');
        }

        const order = await Order.findById(orderId);
        if (!order) {
            throw new ApiError(404, '订单不存在');
        }

        order.status = status;
        await order.save();

        return order;
    }
}

module.exports = new OrderService(); 